<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px;">
      <div style="display:flex;justify-content:space-between;">
        <div>
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">分发软件</el-button>
        </div>
      </div>
      <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
        <el-table-column label="序号" width="60" type="index"
          :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
        <el-table-column label="软件名称" prop="Name" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column label="软件大小" prop="FileSize"  align="left" show-overflow-tooltip></el-table-column>
        <el-table-column label="适用系统" show-overflow-tooltip prop="OSClass"  align="left"></el-table-column>
        <el-table-column label="系统类型" show-overflow-tooltip prop="OSType"  align="left">
          <template slot-scope="{row}">
            {{ row.OSType == '' ? '全部' :  row.OSType}}
          </template>
        </el-table-column>
        <el-table-column label="运行参数" show-overflow-tooltip prop="RunParam"  align="left"></el-table-column>
        <el-table-column label="软件描述" show-overflow-tooltip prop="Descp"  align="left"></el-table-column>
        <el-table-column label="安装成功标准" width="120px" show-overflow-tooltip prop="DeviceObjType"  align="left">
          <template slot-scope="{row}">
            {{ row.SuccessStandard === 0 ? '执行就成功' :  row.SuccessStandard === 1 ? '存在指定文件' : row.SuccessStandard === 2 ? '存在指定注册表项':'添加/删除程序名称'}}
          </template>
        </el-table-column>
        <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObjType"  align="left">
          <template slot-scope="{row}">
            {{ row.DeviceObjType === 1 ? '全部' :  row.DeviceObjType === 2 ? '校区' : '资产'}}
          </template>
        </el-table-column>
        <el-table-column label="具体对象" show-overflow-tooltip prop="DeviceObj" width="160px" align="left">
        <template slot-scope="{row}">
          <span>{{ row.DeviceObj.length === 0 ? '全部' : row.DeviceObj.join(',') }}</span>
        </template>
      </el-table-column>
        <el-table-column label="分发时间" show-overflow-tooltip prop="CreateTime"  align="left"></el-table-column>
        <el-table-column label="执行总数" prop="TotalDeviceCount" width="120" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column label="执行成功数量" prop="ExecSuccessCount" width="120" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column label="执行失败数量" prop="ExecFailCount" width="120" align="left" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column label="执行状态" show-overflow-tooltip prop="ExecDeviceCount"  align="left">
          <template slot-scope="{row}">
            {{row.Status}}
            <span :style="{color: row.Status === 0 ? '#909399' : row.Status === 1 ?'#67C23A':'F56C6C'}">{{ row.Status === 0 ? '等待执行' : row.Status === 1 ?'执行成功':'执行失败' }} </span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="left" width="150px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">详情</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog top="15px" :close-on-click-modal="false" :close-on-press-escape=false
      :title="Action === 1 ? '分发软件' : '分发软件'" :visible.sync="dialogVisible" v-el-drag-dialog width="700px">
      <el-form label-width="130px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-row>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='软件名称:' prop="Name">
              <el-input v-model.trim="accountForm.Name" :disabled="Action !== 1" :maxlength="300"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='适用系统:' prop="OSClass">
              <el-select v-model="accountForm.OSClass" style="width:100%" placeholder="请选择适用系统">
                <el-option  label="Windows" value="Windows"></el-option>
                <!-- <el-option  label="Mac" value="Mac"></el-option>
                <el-option  label="Android" value="Android"></el-option>
                <el-option  label="Linux" value="Linux"></el-option> -->
                <el-option  label="Other" value="Other"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='系统类型:' prop="OSType">
              <el-select v-model="accountForm.OSType" style="width:100%" placeholder="请选择系统类型">
                <el-option label="全部" value=""></el-option>
                <el-option label="64" value="64"></el-option>
                <el-option label="32" value="32"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='运行参数:' prop="RunParam">
              <el-input v-model="accountForm.RunParam"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='分发时间:' prop="CreateTime">
              <el-time-picker v-model="accountForm.CreateTime" placeholder="请选择分发时间" format="HH:mm" value-format="HH:mm" style="width:100%"></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="软件描述" prop="Descp">
              <el-input placeholder="请输入软件描述" type="textarea" :rows="3" v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col> 
          <el-col :xs="24" :sm="24" :lg="24"> 
            <el-form-item label='成功条件:' prop="SuccessStandard">
              <el-radio v-model="accountForm.SuccessStandard"  :label="0">执行就成功</el-radio>
              <el-radio v-model="accountForm.SuccessStandard"  :label="1">存在文件</el-radio>
              <el-radio v-model="accountForm.SuccessStandard"  :label="2">存在注册表项</el-radio>
              <el-radio v-model="accountForm.SuccessStandard"  :label="3">添加/删除程序名称</el-radio>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="对应参数" prop="SuccessParam">
              <el-input :disabled="accountForm.SuccessStandard == 0" placeholder="请输入对应参数" type="textarea" :rows="3" v-model="accountForm.SuccessParam"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24"> 
            <el-form-item label='应用对象:' prop="DeviceObjType">
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="1">全部</el-radio>
              <!-- <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="2">指定校区</el-radio> -->
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="8">指定角色</el-radio>
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="6">指定资产</el-radio>
              <el-select v-model="accountForm.DeviceObj" multiple style="width:100%" :placeholder="accountForm.DeviceObjType==1?'全部':'请选择'" :disabled="accountForm.DeviceObjType === 1">
                <el-option
                  v-for="(item,index) in accountForm.DeviceObjType ===6 ?assetList:DeviceObjList"
                  :key="index"
                  :label="item.DeviceName"
                  :value="item.DeviceName">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label='上传软件:'>
              <el-upload
                class="upload-demo"
                action="#"
                :accept="'.exe,.msi'"
                multiple
                ref="upload"
                :on-change="filechange"
                :http-request="uploadFile"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="1"
                :on-exceed="handleExceed"
                :disabled ="Action === 2"
                :file-list="fileList">
                <el-button size="small" type="primary" >点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape=false title="分发详情" :visible.sync="DistributeDialog" v-el-drag-dialog width="1000px">
      <el-table stripe border :data="DistributeData" style="width: 100%; margin-top: 15px" height="550">
        <el-table-column label="序号" width="80" type="index" :index='(index) => { return (index + 1) + (pageNum - 1) * pageSize }'> </el-table-column>
        <el-table-column label="资产名称" prop="DeviceName" width="180" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column label="执行时间" width="180" show-overflow-tooltip prop="CreateTime"  align="left">
          <template slot-scope="{row}">
            <span >{{ !row.CreateTime  ? '等待执行' : row.CreateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行状态" width="100" prop="Status"  align="left" show-overflow-tooltip>
          <template slot-scope="{row}">
            <span :style="{color: row.Status === 0 ? 'rgb(96, 98, 102)' : row.Status === 1 ?'#67C23A':'#F56C6C'}">{{ row.Status === 0 ? '等待执行' : row.Status === 1 ?'执行成功':'执行失败' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行结果"  prop="Descp"  align="left"></el-table-column>
      </el-table>
      <el-pagination 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" 
        :current-page=pageNum
        :page-size=pageSize
        background 
        layout="total, prev, pager, sizes, next, jumper"
        :total="total">
      </el-pagination>
    </el-dialog>
  </div>
</template>
  
<script>
import { connrequest, uploadfile } from '@/api/firstPage'
import { formatBytes, parseTime } from "@/utils/index.js";
import { getToken } from '@/utils/auth' // get token from cookie
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      Moder:{},
      tableData: [],
      Action: 1,
      dialogVisible: false,
      DistributeDialog: false,
      Attach: [],
      fileList: [],
      accountForm: {},
      DeviceObjList: [],
      DistributeData: [],
      assetList: [],
      rules: {
        Name: [
          { required: true, message: "请输入软件名称" }
        ],
        OSClass: [
          { required: true, message: "请选择适用系统", trigger: 'change' }
        ],
      }
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
    this.CenterGetDevice()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {

  },
  methods: {
    async getData() {
      const res = await connrequest('GetSoftwareDispatch')
      res.Data.map(item => {
        item.FileSize = item.FileSize ? formatBytes(item.FileSize) : 0
        // item.CreateTime = parseTime(item.CreateTime)
        return item
      })
      this.tableData = res.Data
    },
    async CenterGetDevice(){
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000000
        },
        Filter:{
          Status: 0,
        }
      }
      const res = await connrequest('CenterGetDevice', data)
      this.assetList = res.Data
    },
    async DeviceObjTypeChange(value){
      this.$set(this.accountForm, 'DeviceObj', '')
      if(value === 1){
        this.DeviceObjList = []
      }else if(value === 2){
        const res = await this.GetSchoolStatusSumTree()
        this.DeviceObjList = [res]
      }else if(value === 8){
        const res = await this.GetRolestatus()
        var arr = []
        res.map(item => {
          var val ={'DeviceName': item.Role}
          arr.push(val)
        })
        this.DeviceObjList = arr
      }else{
        const res = await this.GetDeviceStatusSumTree()
        this.DeviceObjList = [res]
      }
    },
    // 获取校区树
    async GetSchoolStatusSumTree() {
      const res = await connrequest('GetSchoolStatusSumTree')
      return this.transformData(res.Data)
    },
     // 获取角色
    async GetRolestatus() {
      const res = await connrequest('GetParamDictRole')
      return res.Data
    },
    // 获取资产树
    async GetDeviceStatusSumTree() {
      const res = await connrequest('GetDeviceStatusSumTree')
      return this.transformData(res.Data)
    },
    transformData(inputData) {
      const { RootName, PrimArea} = inputData;
        return {
          SubClass: RootName,
          value: RootName,
          level: 1,
          children: PrimArea.map(area => ({
            SubClass: area.PrimAreaName,
            value: area.PrimAreaName,
            level: 2,
            children: area.SecondArea.map(secondArea => ({
              SubClass: secondArea.SecondAreaName,
              value: secondArea.SecondAreaName,
              level: 3,
          }))
        }))
      }
    },
    handleChange(){},
    // 获取子节点的校区
    async lazyLoad(node, resolve){
      if(node.level < 3){
        resolve(node.data) 
      }else{
        const data = {
          Paging:{
            QueryPageNo: 1,
            QueryPageLength: 100000
          },
          Filter:{
            SecondArea: node.label,
          }
        }
        const res = await connrequest('GetSchool', data)
        let arr = []
        res.Data.map(item => {
          arr.push( {SubClass: item.SchoolName, value: item.SchoolName, level: 4, children: undefined} )
        })
        resolve(arr) 
      }
    },
    // 获取子节点的资产
    async lazyLoad2(node, resolve){
      if(node.level < 3){
        resolve(node.data) 
      }else{
        const data = {
          Paging:{
            QueryPageNo: 1,
            QueryPageLength: 100000
          },
          Filter:{
            SecondArea: node.label,
          }
        }
        const res = await connrequest('CenterGetDevice', data)
        let arr = []
        res.Data.map(item => {
          arr.push( {SubClass: item.DeviceName, value: item.DeviceName, level: 4, children: undefined} )
        })
        resolve(arr) 
      }
    },
    addClick() {
      this.Action = 1
      this.dialogVisible = true
      this.$nextTick(() => {
        this.accountForm = {
          OSType: '',
          OSClass: 'Windows',
          DeviceObjType: 1,
          SuccessStandard:0,
          DeviceObj: []
        }
        this.fileList = []
        this.Attach = []
        this.$refs['accountForm'].resetFields();
      })
    },
    async changeClick(row, index) {
      this.Moder =  {...row}
      this.DistributeDialog = true
      this.getModerDetail()
    },
    async getModerDetail(){
      const data = {
        Paging:{
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize,
        },
        Filter:{
          Name: this.Moder.Name
        }
      }
      const res = await connrequest('GetSoftwareDispatchStatus', data)
      this.DistributeData = res.Data
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
        return item
      })
      this.total = res.Paging.TotalCount
    },
    deleteClick(row) {
      this.$confirm('此操作将永久删除该文件分发任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {
          Data: {
            Action: 3,
            Detail: { ...row }
          }
        }
        const res = await connrequest('EditSoftwareDispatch', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submit() {
      if(this.Attach.length !== 1){
        this.$message.error('请上传软件')
        return false
      }
      this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
            if(this.accountForm.DeviceObjType === 2){
            if(!this.accountForm.DeviceObj) {
              this.$message.error('请选择校区')
              return false
            }
          }
          if(this.accountForm.DeviceObjType === 8){
            if(!this.accountForm.DeviceObj) {
              this.$message.error('请选择角色')
              return false
            }
          }
          if(this.accountForm.DeviceObjType === 6){
            if(!this.accountForm.DeviceObj) {
              this.$message.error('请选择资产')
              return false
            }
          }
          let data = {
            Data: {
              Action: this.Action,
              Detail: { 
                ...this.accountForm,
                FileSize: this.FileSize,
                OrigFileName: this.Attach[0].OrigFileName,
                ResFileName: this.Attach[0].ResFileName,
              }
            }
          }
          const res = await connrequest('EditSoftwareDispatch', data)
          if (res.Status.StatusCode === 0) {
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    filechange(file, fileList){
      let arr = []
      fileList.map(item => {
        arr.push({OrigFileName: item.name, ResFileName: item.uid + ''})
      })
      this.Attach = arr
    },
    async uploadFile(file){
      let formData = new FormData();
      formData.append('CmdCode', "UploadSoftwareDispatch");
      formData.append('OrigFileName', file.file.name);
      formData.append('ResFileName', file.file.uid);
      formData.append('file', file.file);
      formData.append('Token', getToken());
      const res = await uploadfile('UploadSoftwareDispatch',formData)
      if(res.Status.StatusCode === 0) {
        this.FileSize = file.file.size
        this.$message.success('文件上传成功')
      }
    },
    handlePreview(){},
    async handleRemove(file, fileList) {
      const data = {
        Data:{
          ResFileName: file.uid
        }
      }
      const res = await connrequest('DeleteSoftwareDispatchAttach', data)
      if(res.Status.StatusCode === 0){
        this.Attach = this.Attach.filter(item => item.uid !== file.uid);
        this.Attach = this.Attach.filter(item => item.ResFileName != file.uid);
        this.FileSize = 0
        this.$message.success('文件删除成功')
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.getModerDetail()
    },
    handleCurrentChange(pageNum){
      this.pageNum = pageNum
      this.getModerDetail()
    },
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.el-dialog__title::before {
  padding-left: 30px;
  /* 调整标题和图标的距离 */
  background-image: url('../../assets/logo.png');
  /* 指定图标路径 */
  background-repeat: no-repeat;
  /* 防止背景图片重复 */
  background-position: left center;
  /* 将图标放在标题左侧中间 */
}
</style>